
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include <libxml/parser.h>
#include <json-glib/json-glib.h>
#include <json-glib/json-gobject.h>
#include <ctype.h>
void *xml2json__object(void *node, void *json)
{
  xmlNodePtr root = node, child = NULL;
  JsonObject *obj_parent = json, *obj = NULL;

  if (root->type == XML_ELEMENT_NODE) {
    obj = json_object_new(); 
    if (!obj_parent) {
      obj_parent = json_object_new(); 
    }
    json_object_set_object_member(obj_parent,
        (char *) root->name, obj);
    child = root->children;
    while (child) {
      if (child->type == XML_TEXT_NODE) {
        if (isprint(child->content[0])) {
          json_object_set_string_member(obj_parent,
              (char *) root->name, (char *) child->content);
        }
      }
      xml2json__object(child, obj);
      child = child->next;
    }
  }
  return obj_parent;
}
char *xml2json__string(const char *src)
{
  xmlDocPtr doc;
  xmlNodePtr root;
  JsonObject *obj = NULL;

  doc = xmlParseDoc((xmlChar *)src);
  root = xmlDocGetRootElement(doc);
 // obj = json_object_new();
  obj = xml2json__object(root, NULL);

  JsonNode *node = NULL;
  char *str;
  node = json_node_init_object(json_node_alloc(), obj);
  //str = json_to_string(node, FALSE);
  str = json_to_string(node, TRUE);
  return str;
}
int xml2json__file(const char *src, const char *dst)
{
  xmlDocPtr doc;
  xmlNodePtr root;
  JsonObject *obj = NULL;

  doc = xmlParseFile(src);
  root = xmlDocGetRootElement(doc);
  //obj = json_object_new();
  obj = xml2json__object(root, NULL);

  JsonNode *node = NULL;
  char *str;
  node = json_node_init_object(json_node_alloc(), obj);
  //str = json_to_string(node, FALSE);
  str = json_to_string(node, TRUE);
  //printf("succeed:\n%s\n", str);
  FILE *fp = fopen(dst, "w");
  size_t size = fwrite(str, 1, strlen(str), fp);
  if (size) {
    printf("succeed:\n%s\n", str);
  }
  fclose(fp);
  return 0;
}
char *xml2json__to_str(void *obj)
{
  JsonObject *json = obj;
  JsonNode *node = NULL;
  char *str;
  node = json_node_init_object(json_node_alloc(), json);
  str = json_to_string(node, TRUE);
  if (node) {
    json_node_unref(node);
  }
  return str;
}
